package everyday.leetcode.editor.cn;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * @Author: Dang Qi
 * @Date: 2021/3/10  12:36
 * @Description: 224. 基本计算器
 */
public class BasicCalculator {

    public static void main(String[] args) {
        Solution solution = new BasicCalculator().new Solution();
        String s = "-2+ 1";
        System.out.println(solution.calculate(s));
        System.out.println(s);
        System.out.println(solution.toHou(s));
    }
    class Solution {
        public int calculate(String s) {

            List<String> sb = toHou(s);
            Stack<Integer> res = new Stack<>();
            for(String t: sb) {
                switch (t){
                    case "-":
                        res.push(-res.pop() + res.pop());
                        break;
                    case "+":
                        res.push(res.pop() + res.pop());
                        break;
                    default:
                        res.push(Integer.parseInt(t));
                }
            }
            return res.pop();
        }
        public List<String> toHou(String s){
            List<String> sb = new LinkedList<>();
            Stack<Character> opStack = new Stack<>();
            Stack<Character> bracketStack = new Stack<>();
            char[] cc = s.trim().toCharArray();
            char last = ' ';
            int i = 0;
            while(i<cc.length){
                if(cc[i]==' ') {
                    i++;
                    continue;
                }
                int temp = i;
                if(cc[i] == '-' || cc[i]=='+'){
                    if(i==0 || last=='(') sb.add("0");
                    opStack.push(cc[i]);
                }else if(cc[i] == '('){
                    bracketStack.push(cc[i]);
                }
                else if(cc[i] == ')'){
                    bracketStack.pop();
                    if(!opStack.isEmpty()) sb.add(opStack.pop()+"");
                }else{
                    int num = cc[i]-'0';
                    while(i+1 < cc.length && cc[i+1]<='9' && cc[i+1]>='0') {
                        num = num*10 + cc[i+1] - '0';
                        i++;
                    }
                    sb.add(num+"");
                    if(i-1>=0 && (last =='-' || last=='+') ) sb.add(opStack.pop()+"");
                }
                last = cc[temp];
                i++;
        }
            return sb;
        }
    }
}
